package cn.cool.service.impl;

import cn.cool.entity.Comment;
import cn.cool.mapper.CommentMapper;
import cn.cool.result.ResponseResult;
import cn.cool.service.CommentService;
import cn.cool.utils.JWTUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Response;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LiuH
 * @since 2021-01-23
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    /**
     * 添加评论
     *
     * @param request
     * @param comment
     * @return
     */
    @Override
    public Object addComment(HttpServletRequest request, Comment comment) {
        //获取发表评论的用户id
        Integer userId = JWTUtils.getUserId(request);
        comment.setUserId(userId);

        //一级评论不传 parentCommentId
        if (comment.getParentCommentId() == null) { //说明是一级评论
            //发送一级评论
            return sendLevelOne(comment);
        }

        // 说明是 回复一级评论 的 二级评论 / 回复二级评论 的 二级评论
        return replyComment(comment);

    }

    /**
     * 发送一级评论
     *
     * @param comment
     * @return
     */
    private Object sendLevelOne(Comment comment) {

        if (comment.getContent().trim().length() == 0) {
            return ResponseResult.failure("请输入评论内容");
        }

        //设置级别为 一级
        comment.setCommentLevel(1);
        //评论时间
        comment.setGmtCreate(new Date());

        //插入数据库
        int result = commentMapper.insertSelective(comment);

        if (result > 0) {
            return ResponseResult.success(200, "发表成功!");
        }

        return ResponseResult.failure("发表失败,请重新试试吧");

    }

    /**
     * 回复 一级评论/二级评论
     *
     * @param comment
     * @return
     */
    private Object replyComment(Comment comment) {

        if (comment.getContent().trim().length() == 0) {
            return ResponseResult.failure("请输入评论内容");
        }
        //设置级别为 二级
        comment.setCommentLevel(2);
        //评论时间
        comment.setGmtCreate(new Date());

        //插入数据库
        int result = commentMapper.insertSelective(comment);

        if (result > 0) {
            return ResponseResult.success(200, "发表成功!");
        }

        return ResponseResult.failure("发表失败,请重新试试吧");

    }

}
